<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        * {
            padding: 0;
            margin: 0;
            list-style: none;
            box-sizing: border-box;
        }
        body {
            width: 100%;
            background-color: rgb(5, 63, 255);
        }
        header {
            width: 50%;
            margin: 30px auto;
            color: white;
            text-align: center;
            font-size: 15px;
        }
        .search {
            margin-top: 20px;
            width: 100%;
            height: 35px;
            padding: 0 10px;
        }
        .search:focus {
            outline: none;
        }
        section {
            width: 50%;
            margin: 0 auto;
            text-align: left;
        }
        .bodys {
            width: 100%;
        }
        .bodys li {
            width: 100%;
            color: white;
            background-color: rgb(52, 140, 255);
            margin-bottom: 30px;
            font-size: 15px;
            padding: 15px 30px;
            border-radius: 5px;
            box-shadow: 0px 1px 1px 1px rgb(1, 17, 68);
            position: relative;
        }
        .bodys li h2 {
            margin-bottom: 10px;
        }
        /* 序号 */
        .serial {
            display: inline-block;
            width: 30px;
            height: 30px;
            border-radius: 50%;
            position: absolute;
            top: -10px;
            left: -10px;
            color: rgb(5, 63, 255);
            text-align: center;
            line-height: 30px;
            background-color: white;
        }
        .more {
            display: flex;
            width: 50px;
            justify-content: space-between;
            margin: 0px auto;
        }
        .more li {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background-color: white;
            margin: 20px 0;
        }
        .bottom {
            display: inline-block;
            width: 100%;
            text-align: center;
            color: white;
            font-size: 20px;
            margin-bottom: 30px;
        }
        @keyframes btn {
            0% {
                transform: translate(0);
            }
            25% {
                transform: translate(0, -10px);
            }
            50% {
                transform: translate(0);
            }
            75% {
                transform: translate(0, 10px);
            }
            100% {
                transform: translate(0);
            }
        }
        .animation1 {
            display: none;
            animation: btn 1s linear 0s infinite;
        }
        .animation2 {
            display: none;
            animation: btn 1s linear 0.2s infinite;
        }
        .animation3 {
            display: none;
            animation: btn 1s linear 0.4s infinite;
        }
        /* 显示动画 */
        .show_btn {
            display: inline-block;
        }
        /* 下面是回到顶部样式 */
        .rocket {
            width: 148px;
            height: 249px;
            background-image: url(./img/QQ图片20210803160339.png);
            position: fixed;
            right: 0;
            bottom: 0px;
        }
        .rocket:hover {
            background-position: -148px 0;
        }
        .active {
            animation: fire 1s infinite steps(4);
        }
        @keyframes fire {
            0% {
                background-position: -296px 0;
            }
            100% {
                background-position: -892px 0;
            }
        }
    </style>
    <title>Document</title>
</head>
<body>
    <header>
        <div class="head">
            <h1>我的博客</h1>
            <input type="text" class="search" placeholder="查询帖子...">
        </div>
    </header>
    <section>
        <ul class="bodys"></ul>
        <ul class="more">
            <li class="animation1"></li>
            <li class="animation2"></li>
            <li class="animation3"></li>
        </ul>
    </section>
    <div class="rocket"></div>
    <script>
        let uls = document.querySelector('.bodys');
        let lis = document.querySelectorAll('.more li');
        let rocket = document.querySelector('.rocket');
        let search = document.querySelector('.search');
        // 1. 先用ajax获取到数据，然后根据数据的内容渲染页面
        // 这个事ajax请求函数
        function ajax_fn (method, url, data, cb) {
            let xhr = new XMLHttpRequest();
            let newurl = url;
            if (method === 'GET') {
                newurl += "?";
                for(let key in data) {
                    newurl += `${key}=${data[key]}&`;
                }
                newurl = newurl.slice(0, -1);
                xhr.open(method, newurl);
                xhr.send();
            } else if (method === 'POST') {
                let str = "";
                for (let key in data) {
                    str += `${key}=${data[key]}&`;
                }
                str = str.slice(0, -1);
                xhr.open(method, newurl);
                xhr.setRequestHeader('Content-Type', "application/x-www-form-urlencoded")
                xhr.send(str);
            }
            xhr.addEventListener('readystatechange', function() {
                if (xhr.readyState == 4) {
                    if (xhr.status == 200) {
                        let objs = JSON.parse(xhr.responseText);
                        cb(objs);
                    }
                }
            })
        }
        let url = "http://jsonplaceholder.typicode.com/posts";
        let data = {
            _limit:20,
            _page:1
        }
        ajax_fn("GET", url, data, renderer);
        // 定义数组来存储已将渲染在页面的数据
        let newArr = [];
        // 渲染dom页面
        function renderer(obj) {
            console.log(obj);
            // 加载到数据之后隐藏加载动画
            lis.forEach(function(ele) {
                ele.classList.remove('show_btn');
            });
            obj.forEach(function(item) {
                newArr.push(item);
                uls.innerHTML += `<li>
                                        <h2>${item.title}</h2>
                                        <p>${item.body}</p>
                                        <span class="serial">${item.id}</span>
                                </li>
                                `
            }) 
        }
        // 定时器
        // let timer = null;
        // 监听滚动条滚动事件
        document.addEventListener('scroll', myThrottle(isBottom, 3000));

        // 判断滚条是否到达底部
        function isBottom() {
            // 页面内容的高度，包括被滚动条卷去的
            let contentHeight = document.documentElement.scrollHeight;
            // 被滚动条卷去的高度
            let topHeight = document.documentElement.scrollTop;
            // 窗口的可视高度
            let windowHeight = document.documentElement.clientHeight;
            // 当可视高度 + 被卷去高度 = 内容高度 时滚动条已到达底部
            if (windowHeight + topHeight == contentHeight) {
                // if (!timer) {
                    // // 显示加载动画
                    lis.forEach(function(ele) {
                        ele.classList.add('show_btn');
                    });
                    // timer = setTimeout(function() {
                        // 判断是否到达最后一页
                        if (data._page * 20 < 100) {
                            data._page += 1;
                            ajax_fn("GET", url, data, renderer);
                            // 到达最后一页时显示已到达底部
                        } else if (data._page * 20 == 100) {
                            data._page += 1;
                            uls.innerHTML += `<span class='bottom'>已到达底部</span>`
                            console.log(11);
                        } else {
                            // 隐藏加载动画
                            lis.forEach(function(ele) {
                                ele.classList.remove('show_btn');
                            });
                        }
                        timer = null;
                        // console.log(newArr);
                    // }, 1000);
                // }
            }
        }

        // 节流函数封装
        function myThrottle(handle, wait) {
            let previous = new Date(); //保存上一次执行时间
            let timer = null;
            return function proxy() {
                let now = new Date()// 触发事件的时间
                let interval = wait - (now - previous)
                if(interval <= 0) {
                    // 这里就是为了避免定义的时间刚好和浏览器触发的时间相同
                    clearTimeout(timer);
                    timer = null;
                    console.log('111');//测试
                    handle()
                    // 为了方便计算下一次
                    // 要对当前时间记录
                    previous = new Date(); 
                } else if (!timer) {
                    // 没到500 不要执行
                    timer = setTimeout(function() {
                        clearTimeout(timer);
                        timer = null;
                        console.log('222')//测试
                        handle();
                        previous = new Date();
                    }, interval)
                }
            }
        }

        // 回到顶部事件
        rocket.addEventListener('click', function() {
            rocket.classList.add('active');
            // 求S火
            let rocket_distance = rocket.offsetTop + 250;
            // 求S滚
            let scroll_distance = document.documentElement.scrollTop;
            // 求V火
            let rocket_v = rocket_distance / 50;
            // 求V滚
            let scroll_v = scroll_distance / 50;
            let timer = setInterval(function() {
                // rocket 要修改 rocket.style.top
                rocket.style.top = `${rocket.offsetTop - rocket_v}px`
                document.documentElement.scrollTop -= scroll_v;
                if(document.documentElement.scrollTop == 0) {
                    clearInterval(timer);
                    rocket.style.top = "";
                    rocket.classList.remove("active");
                }
            }, 20);
        });
        
        // 防抖函数封装
        function myDebounce(handle, wait, immediate) {
            let timer = null;
            let init = null;
            return function proxy() {
                let that = this;
                let args = arguments;
                init = immediate && !timer;
                clearTimeout(timer);
                timer = setTimeout(function() {
                    timer = null;
                    !immediate ? handle.call(that, args[0]) : null;
                }, wait);
                init ? handle.call(that, args[0]) : null;
            }
        }

        // 筛选执行的函数
        function searchfn(e) {
            let str = search.value;
            if (str == "") {
                return;
            }
            console.log(str);
            uls.innerHTML = "";
            newArr.forEach(function(item) {
                // console.log(item.title);
                if(item['title'].includes(str) || item['body'].includes(str)) {
                    uls.innerHTML += `
                                        <li>
                                            <h2>${item.title}</h2>
                                            <p>${item.body}</p>
                                            <span class="serial">${item.id}</span>
                                        </li>
                                        `
                }
            }) 
        }
        // 筛选
        search.addEventListener('keyup', myDebounce(searchfn, 3000, false));

    </script>
</body>
</html>